package api

import (
	"gitee.com/enzolwb/my-web-scaffold/models"
	"gitee.com/enzolwb/my-web-scaffold/pkg/app"
	"gitee.com/enzolwb/my-web-scaffold/pkg/app/validation"
	"gitee.com/enzolwb/my-web-scaffold/pkg/ecode"
	"github.com/gin-gonic/gin"
)

/*
	演示Demo 可删除
	主要作用是参考 验证、JWT、统一返回值等写法
*/
type AuthInput struct {
	Username string `form:"username" json:"username" binding:"required,max=20,min=4" comment:"用户名"`
	Password string `form:"password" json:"password" binding:"omitempty,min=4" comment:"密码"`
}

func GetAuth(c *gin.Context) {
	var (
		obj  AuthInput
		err  error
		auth *models.Auth
	)
	if err := validation.BindValidParams(c, &obj); err != nil {
		return
	}
	data := make(map[string]string)
	code := ecode.XError
	auth, err = models.CheckAuth(obj.Username, obj.Password)
	if err == nil {
		token, err := app.GenerateToken(obj.Username, obj.Password)
		if err != nil {
			code = ecode.ErrGenTokenFail
		} else {
			data["token"] = token
			data["user_name"] = auth.UserName
			code = ecode.Ok
		}
	} else {
		code = ecode.ErrAuthNotFind
	}
	app.Response(c, code, data)
	return
}
